package com.tpc.pictool.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PNGResizeExample {
    public static void pngResizeExample(String fileName) throws IOException {
        // 读取PNG文件
        File inputFile = new File(fileName);
        BufferedImage inputImage = ImageIO.read(inputFile);

        // 计算A4纸张大小（72 DPI）
        int width = (int) (8.27 * 72);
        int height = (int) (11.69 * 72);

        // 计算缩放比例
        double scaleX = (double) width / inputImage.getWidth();
        double scaleY = (double) height / inputImage.getHeight();
        double scale = Math.min(scaleX, scaleY);

        // 创建新的缩放后的图像
        BufferedImage outputImage = new BufferedImage((int) (inputImage.getWidth() * scale),
                (int) (inputImage.getHeight() * scale),
                inputImage.getType());
        Graphics2D g2d = outputImage.createGraphics();
        g2d.drawImage(inputImage, 0, 0, outputImage.getWidth(), outputImage.getHeight(), null);
        g2d.dispose();

        // 将缩放后的图像保存到文件
        File outputFile = new File(fileName);
        ImageIO.write(outputImage, "png", outputFile);
    }
}
